package cn.wildfire.chat.app.extendsion.classes;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sourcemuch.im.caiba.InterfaceReceiversHub;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import org.json.JSONObject;

import java.util.HashMap;

import cn.wildfire.chat.app.Config;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.SPUtils;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.login.model.LoginResult;
import cn.wildfire.chat.app.main.LoginActivity;
import cn.wildfire.chat.app.main.MainActivity;
import cn.wildfire.chat.kit.ChatManagerHolder;
import cn.wildfirechat.remote.ChatManager;

/**
 * Create by HEKE, 2019/9/10 17:28
 * TODO 登录对象
 */
public class LoginRequest {

    public LoginRequest(Activity activity, String account, String password2, Region currentRegion, boolean remenberTag) {
        login(activity, account, password2, currentRegion, remenberTag);
    }

    /**
     * 密码登入
     *
     * @param activity
     * @param account
     * @param password2
     * @param currentRegion
     * @param remenberTag
     */
    private void login(Activity activity, String account, String password2, Region currentRegion, boolean remenberTag) {
        try {
            if (TextUtils.isTextEmpty(account) || TextUtils.isTextEmpty(password2)) {
                Toast.makeText(activity, activity.getString(R.string.input_total_msg), Toast.LENGTH_SHORT).show();
                return;
            }
            if (password2.length() < 6) {
                Toast.makeText(activity, activity.getString(R.string.password_length_invalid), Toast.LENGTH_SHORT).show();
                return;
            }
            MaterialDialog dialog = new MaterialDialog.Builder(activity)
                    .content(activity.getString(R.string.logining_msg))
                    .progress(true, 100)
                    .cancelable(false)
                    .build();
            dialog.show();

            HashMap<String, String> params = new HashMap<>();
            params.put("clientId", "" + ChatManager.Instance().getClientId());
            params.put("mobile", account);
            params.put("password", password2);
            params.put("regionId", "" + currentRegion.id);
            OkHttpRequest.getInstance(activity).requestAsyn(ServerUrlClient.PASSWORD_LOGIN, OkHttpRequest.TYPE_POST_JSON, params,
                    new ReqCallBack<Object>() {
                        @SuppressLint("ApplySharedPref")
                        @Override
                        public void onReqSuccess(Object result) {
                            try {
                                dialog.dismiss();
                                String ret = result.toString();
                                ResponseEntity<String, String> responseEntity = new ResponseEntity<>(result.toString());
                                if (responseEntity.getErrorCode().equals("0")) {
                                    LoginResult loginResult = new LoginResult();
                                    JSONObject jsonObject = new JSONObject(ret);
                                    JSONObject entry = jsonObject.getJSONObject("result");
                                    loginResult.setToken(entry.getString("token"));
                                    loginResult.setUserId(entry.getString("userId"));
                                    String checkSetEncrypted = entry.getString("checkSetEncrypted");
                                    String userId = loginResult.getUserId();
                                    // 设置账号对应缓存路径
                                    Config.setCurrentLoginUserIdForCacheSet(loginResult.getUserId());
                                    // 刷新和连接服务
                                    ChatManagerHolder.gChatManager.connect(loginResult.getUserId(), loginResult.getToken());
                                    // 保存账号密码、登录信息
                                    SPUtils.setMuches(activity, "config",
                                            new String[]{"id", "token"}, new String[]{loginResult.getUserId(), loginResult.getToken()});
                                    if (remenberTag) {
                                        SPUtils.setMuches(activity, "REMENBER_CONTENT",
                                                new String[]{"account", "password", "region"}, new String[]{account, password2, currentRegion.toSimpleString()});
                                    } else {
                                        SPUtils.setMuches(activity, "REMENBER_CONTENT",
                                                new String[]{"account", "password", "region"}, new String[]{account, "", currentRegion.toSimpleString()});
                                    }
                                    ChatManager.Instance().getUserInfo(loginResult.getUserId(), true);
                                    // 注册推送账号
                                    InterfaceReceiversHub.setMiPushAccount(activity, userId);

                                    if (activity instanceof LoginActivity) {
                                        LoginActivity loginActivity = (LoginActivity) activity;
                                        if ("0".equals(checkSetEncrypted)) {
                                            loginActivity.ShowPopWindow();
                                        } else {
                                            //如果已经设置过密保
                                            // 进入主界面
                                            Intent intent = new Intent(activity, MainActivity.class);
                                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                            activity.startActivity(intent);
                                            activity.finish();
                                        }
                                    } else {
                                        // 进入主界面
                                        Intent intent = new Intent(activity, MainActivity.class);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        activity.startActivity(intent);
                                        activity.finish();
                                    }

                                } else {
                                    JSONObject jsonObject = new JSONObject(ret);
                                    String message = jsonObject.getString("message");
                                    ToastTip.tip("登录失败!" + message);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            dialog.dismiss();
                            ToastTip.tip("登录失败!" + errorMsg);
                        }
                    }).request();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
